﻿Friend Class ScanFolder_Common
    Public Shared Function UpdateSharedFileIfChanged(ByVal fileInfo As IO.FileInfo, ByVal file As Entities.SharedItemFile, ByVal transactionScope As DataStore.TransactionScope) As Boolean
        Dim blnHasChanged As Boolean = False
        If fileInfo.Length <> file.Size Then blnHasChanged = True
        Dim tsDiff As TimeSpan = fileInfo.LastWriteTimeUtc.Subtract(file.LastChanged)
        If Math.Abs(tsDiff.TotalSeconds) > 1 Then blnHasChanged = True

        If blnHasChanged Then
            file.LastChanged = fileInfo.LastWriteTimeUtc
            file.Size = fileInfo.Length
            file.SHA512Hash = Utils.Hash.ComputeSHA512Hash(fileInfo.FullName)

            DataStore.SharedItemsFiles.Save(file, transactionScope)
            Return True
        Else
            Return False
        End If
    End Function

    Public Shared Function CreateSharedItemFile(ByVal fileInfo As IO.FileInfo) As Entities.SharedItemFile
        'first, try to see if we already know the SHA512 hash by searching for existing information

        Dim strFilename As String = IO.Path.GetFileName(fileInfo.FullName)
        Dim dtLastChangedUtc As Date = fileInfo.LastWriteTimeUtc
        Dim lSize As Long = fileInfo.Length
        Dim clsItemFile As Entities.SharedItemFile = Nothing
        Dim strSHA512Hash As String = Nothing

        'try to reuse sha512-information from existing files only if size is larger than 1 Mb
        If lSize < 1024 * 1024 Then
            Manager.OnLogEvent(String.Format("Calculating SHA512-hash for file {0}...", fileInfo.FullName))
            strSHA512Hash = Utils.Hash.ComputeSHA512Hash(fileInfo.FullName)

            Dim aExisting As Generic.List(Of Entities.SharedItemFile)
            aExisting = DataStore.SharedItemsFiles.GetAllBySHA512Hash(strSHA512Hash)
            For Each clsExistingFile As Entities.SharedItemFile In aExisting
                If clsExistingFile.SharedItemId = 0 Then
                    clsItemFile = clsExistingFile
                    Exit For
                End If
            Next

        Else
            Dim aExisting As Generic.List(Of Entities.SharedItemFile)
            aExisting = DataStore.SharedItemsFiles.GetAllByFileNameAndSize(strFilename, lSize)

            For Each clsExistingFile As Entities.SharedItemFile In aExisting
                If clsExistingFile.LastChanged = dtLastChangedUtc Then
                    clsItemFile = clsExistingFile
                    Exit For
                End If
            Next
        End If

        If clsItemFile IsNot Nothing Then
            Manager.OnLogEvent(String.Format("Found orphaned file with right name, size, and timestamp. Reusing information for {0}.", fileInfo.FullName))
            clsItemFile.Added = Now.ToUniversalTime
            clsItemFile.Directory = fileInfo.DirectoryName
            clsItemFile.LastChanged = dtLastChangedUtc
        Else
            clsItemFile = New Entities.SharedItemFile
            clsItemFile.Added = Now.ToUniversalTime
            clsItemFile.FileName = strFilename
            clsItemFile.LastChanged = dtLastChangedUtc
            clsItemFile.Directory = fileInfo.DirectoryName
            clsItemFile.Size = lSize
            If strSHA512Hash Is Nothing Then
                Manager.OnLogEvent(String.Format("Calculating SHA512-hash for file {0}...", fileInfo.FullName))
                clsItemFile.SHA512Hash = Utils.Hash.ComputeSHA512Hash(fileInfo.FullName)
            Else
                clsItemFile.SHA512Hash = strSHA512Hash
            End If
        End If
        Return clsItemFile
    End Function
    Public Shared Function CreateSharedItemFile(ByVal filename As String) As Entities.SharedItemFile
        Return CreateSharedItemFile(New IO.FileInfo(filename))
    End Function

    Public Shared Function GetAllFileInfosRecursive(ByVal path As String) As Generic.Dictionary(Of String, IO.FileInfo)
        Dim aRet As New Generic.Dictionary(Of String, IO.FileInfo)
        AddAllFileInfosRecursive(path, aRet)
        Return aRet
    End Function


    Private Shared Sub AddAllFileInfosRecursive(ByVal currentPath As String, ByVal dict As Generic.Dictionary(Of String, IO.FileInfo))
        For Each strFilename As String In IO.Directory.GetFiles(currentPath)
            Dim clsFI As New IO.FileInfo(strFilename)
            dict.Add(strFilename.ToLower, clsFI)
        Next
        For Each strSubDir As String In IO.Directory.GetDirectories(currentPath)
            AddAllFileInfosRecursive(strSubDir, dict)
        Next
    End Sub

    Public Shared Function CreateMediaInfoEx(ByVal item As Entities.SharedItem) As Entities.MediaInfo
        Return CreateMediaInfoEx(item, Nothing)
    End Function

    Public Shared Function CreateMediaInfoEx(ByVal item As Entities.SharedItem, ByVal files As Generic.List(Of Entities.SharedItemFile)) As Entities.MediaInfo
        Select Case item.ItemType
            Case Entities.ItemType.Movies
            Case Else
                Return Nothing
        End Select

        Dim aFiles As Generic.List(Of Entities.SharedItemFile)
        If files Is Nothing Then
            aFiles = DataStore.SharedItemsFiles.GetAllBySharedItemId(item.Id)
        Else
            aFiles = files
        End If

        'first, if omx file exists, load it and save it
        Dim strOmxFile As String = Nothing
        For Each clsFile As Entities.SharedItemFile In aFiles
            If IO.Path.GetExtension(clsFile.FileName).ToLower = ".omx" Then
                strOmxFile = IO.Path.Combine(clsFile.Directory, clsFile.FileName)
                Exit For
            End If
        Next

        Dim clsMI As Entities.OpenMediaInfo.OpenMediaInfo = Nothing

        If strOmxFile IsNot Nothing Then
            Dim strXml As String
            Using fs As New IO.FileStream(strOmxFile, IO.FileMode.Open)
                Using sr As New IO.StreamReader(fs)
                    strXml = sr.ReadToEnd
                End Using
            End Using
            clsMI = Utils.Serialization.FromXml(Of Entities.OpenMediaInfo.OpenMediaInfo)(strXml)
        End If

        Dim blnUpToDate As Boolean = False
        If clsMI IsNot Nothing Then
            If clsMI.Version >= 2 Then blnUpToDate = True
            If clsMI.Feature Is Nothing Then blnUpToDate = False
        End If
        If Not blnUpToDate Then
            'if omx file is missing, load info from media files

            Dim aFileNames As New Generic.List(Of String)
            For Each clsFile As Entities.SharedItemFile In aFiles
                aFileNames.Add(IO.Path.Combine(clsFile.Directory, clsFile.FileName))
            Next

            Dim clsUri As System.Uri = Nothing
            If clsMI IsNot Nothing AndAlso clsMI.Feature IsNot Nothing Then
                For Each strId As String In clsMI.Feature.Ids
                    If strId.StartsWith("imdb:") Then
                        Dim strUrl As String = strId.Replace("imdb:", "http://www.imdb.com/title/") & "/"
                        clsUri = New Uri(strUrl)
                        Exit For
                    End If
                Next
            End If

            Dim clsOldMI As Entities.OpenMediaInfo.OpenMediaInfo = clsMI
            If clsUri IsNot Nothing Then
                clsMI = OpenMediaInfo.Manager.GenerateForMovie(clsUri, aFileNames.ToArray)
            Else
                clsMI = OpenMediaInfo.Manager.GenerateForMovie(aFileNames.ToArray)
            End If
            'If strOmxFile Is Nothing Then strOmxFile = OpenMediaInfo.Manager.GetSuggestedOMXFileName(item, aFileNames.ToArray)
            'If strOmxFile IsNot Nothing Then
            '    Dim strXml As String = Utils.Serialization.ToXml(clsMI)
            '    Utils.IO.SaveTextFileUnicode(strOmxFile, strXml)
            'End If
        End If

        Dim clsMIE As New Entities.MediaInfo
        clsMIE.SharedItemId = item.Id
        If clsMI.Feature IsNot Nothing Then
            clsMIE.FeatureTitle = clsMI.Feature.Title
            clsMIE.Genres = New Generic.List(Of String)
            For Each clsGenre As Entities.OpenMediaInfo.Genre In clsMI.Feature.Genres
                clsMIE.Genres.Add(clsGenre.Name)
            Next
        End If
        clsMIE.Version = clsMI.Version
        clsMIE.OpenMediaInfo = clsMI
        Return clsMIE
    End Function

    Private Shared Function AreEqual(ByVal omi1 As Entities.OpenMediaInfo.OpenMediaInfo, ByVal omi2 As Entities.OpenMediaInfo.OpenMediaInfo) As Boolean



    End Function




End Class
